// 云存储文件清理工具函数

/**
 * 从记录中提取所有文件URL
 * @param {Object} record - 数据库记录
 * @param {Array} fileFields - 文件字段名数组
 * @returns {Array} 文件URL数组
 */
function extractFileUrls(record, fileFields = ['logo', 'banner', 'image', 'photo', 'images', 'attachment', 'attachments']) {
	const fileUrls = []
	
	if (!record) return fileUrls
	
	fileFields.forEach(field => {
		const value = record[field]
		
		if (!value) return
		
		// 处理单个file对象
		if (typeof value === 'object' && value.url) {
			fileUrls.push(value.url)
		}
		// 处理字符串URL
		else if (typeof value === 'string' && value.startsWith('cloud://')) {
			fileUrls.push(value)
		}
		// 处理数组
		else if (Array.isArray(value)) {
			value.forEach(item => {
				if (typeof item === 'object' && item.url) {
					fileUrls.push(item.url)
				} else if (typeof item === 'string' && item.startsWith('cloud://')) {
					fileUrls.push(item)
				}
			})
		}
	})
	
	return fileUrls
}

/**
 * 删除云存储文件
 * @param {Array} fileUrls - 文件URL数组
 * @returns {Object} 删除结果
 */
async function deleteCloudFiles(fileUrls) {
	if (!fileUrls || fileUrls.length === 0) {
		return {
			code: 200,
			message: '无文件需要删除',
			data: { total: 0, success: 0, failed: 0 }
		}
	}
	
	try {
		const result = await uniCloud.deleteFile({
			fileList: fileUrls
		})
		
		let successCount = 0
		let failCount = 0
		
		if (result.fileList && Array.isArray(result.fileList)) {
			result.fileList.forEach(file => {
				if (file.code === 0) {
					successCount++
				} else {
					failCount++
					console.error(`文件删除失败 - ${file.fileID}:`, file.message)
				}
			})
		}
		
		return {
			code: 200,
			message: `文件删除完成：成功${successCount}个，失败${failCount}个`,
			data: {
				total: fileUrls.length,
				success: successCount,
				failed: failCount,
				details: result.fileList
			}
		}
	} catch (err) {
		console.error('[deleteCloudFiles] 删除云存储文件失败:', err)
		return {
			code: 500,
			message: err.message || '删除文件失败',
			data: null
		}
	}
}

/**
 * 从数据库记录中提取并删除所有关联文件
 * @param {Object} record - 数据库记录
 * @param {Array} fileFields - 文件字段名数组（可选）
 * @returns {Object} 删除结果
 */
async function cleanupRecordFiles(record, fileFields) {
	const fileUrls = extractFileUrls(record, fileFields)
	
	if (fileUrls.length === 0) {
		return {
			code: 200,
			message: '该记录无关联文件',
			data: null
		}
	}
	
	console.log(`[cleanupRecordFiles] 准备删除文件:`, fileUrls)
	return await deleteCloudFiles(fileUrls)
}

/**
 * 批量清理记录的关联文件
 * @param {Array} records - 数据库记录数组
 * @param {Array} fileFields - 文件字段名数组（可选）
 * @returns {Object} 删除结果
 */
async function batchCleanupRecordFiles(records, fileFields) {
	if (!records || records.length === 0) {
		return {
			code: 200,
			message: '无记录需要处理',
			data: null
		}
	}
	
	const allFileUrls = []
	
	records.forEach(record => {
		const urls = extractFileUrls(record, fileFields)
		allFileUrls.push(...urls)
	})
	
	// 去重
	const uniqueFileUrls = [...new Set(allFileUrls)]
	
	console.log(`[batchCleanupRecordFiles] 批量清理文件，共${uniqueFileUrls.length}个`)
	return await deleteCloudFiles(uniqueFileUrls)
}

/**
 * 获取表对应的文件字段映射
 * @param {string} tableName - 表名
 * @returns {Array} 文件字段数组
 */
function getTableFileFields(tableName) {
	const fileFieldsMap = {
		'dh-hospitals': ['logo', 'banner'],
		'dh-doctors': ['photo'],
		'dh-nurses': [],
		'dh-staff_users': [],
		'dh-patients': [],
		'dh-services': ['image'],
		'dh-products': ['image'],
		'dh-doctor_schedules': [],
		'dh-appointments': [],
		'dh-medical_records': ['images'],
		'dh-reviews': ['images'],
		'dh-consultations': ['images'],
		'dh-income_records': [],
		'dh-leave_requests': ['attachment'],
		'dh-purchase_requests': ['attachments'],
		'dh-inventory': [],
		'dh-inventory_logs': [],
		'dh-hospital_promotions': ['image'],
		'dh-hospital_banners': ['image'],
		'dh-promotion_rules': [],
		'dh-medical_authorizations': []
	}
	
	return fileFieldsMap[tableName] || []
}

module.exports = {
	extractFileUrls,
	deleteCloudFiles,
	cleanupRecordFiles,
	batchCleanupRecordFiles,
	getTableFileFields
}

